package com.reggie.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.reggie.common.R;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${reggie.basePath}")
    private File path;

    @PostMapping("/upload")
    //上传图片到服务器中
    //请求参数必须时这个MultipartFile
    public R<String> upload(MultipartFile file) {
        try {
            if (!path.exists()) {
                //在传输之前先判断一下这个路径的文件夹存不存在如果不存在创建这个文件夹
                path.mkdir();
            }
            //此处的file文件是一个临时的文件当这次的请求放行时这个file文件就会消失
            String pathLast = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String dishName = UUID.randomUUID().toString();
            file.transferTo(new File(path + "\\" + dishName + "." + pathLast));
            return R.success(dishName + "." + pathLast);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            //定义response的传输协议
            response.setContentType("image/jpeg");
            //使用输入流和输出流将图片输出到客户端
            FileInputStream fis = new FileInputStream(path + "\\" + name);
            ServletOutputStream os = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
